package com.easy.controller;

import com.easy.bean.UserBean;
import com.easy.service.UserService;
import com.easy.util.EmailUtil;
import com.easy.util.Page;
import com.easy.util.Result;
import com.easy.util.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    VerificationCodeService verificationCodeService;

    @PostMapping("register")
    public Result register(@RequestBody UserBean user) {
        // 检查账号是否已存在
        UserBean existingUser = userService.getByNumber(user.getUserNumber());
        if (existingUser != null) {
            return Result.fail(200, "账号已存在");
        }

        // 验证必要字段
        if (user.getUserNumber() == null || user.getUserNumber().isEmpty()) {
            return Result.fail(400, "账号不能为空");
        }
        if (user.getUserPassword() == null || user.getUserPassword().isEmpty()) {
            return Result.fail(400, "密码不能为空");
        }
        if (user.getUserNickname() == null || user.getUserNickname().isEmpty()) {
            return Result.fail(400, "昵称不能为空");
        }

        // 设置默认值
        if (user.getUserSect() == null || user.getUserSect().isEmpty()) {
            user.setUserSect("未知");
        }

        try {
            UserBean newUser = userService.add(user);
            return Result.success("注册成功", newUser);
        } catch (Exception e) {
            return Result.fail(500, "注册失败: " + e.getMessage());
        }
    }
    @GetMapping("info/{id}")
    public Result getUserInfo(@PathVariable("id") Integer id) {
        UserBean user = userService.getUserInfo(id);
        return user != null ? Result.success(user) : Result.fail(200,"用户不存在或已被删除");
    }

    @PostMapping("add")
    public Result add(@RequestBody UserBean user){
        UserBean user_data = userService.add(user);
        return Result.success(user_data);
    }

    @PutMapping
    public Result edit(@RequestBody UserBean user){
        UserBean user_data = userService.edit(user);
        return Result.success("编辑成功"+user_data);
    }

    @DeleteMapping("{id}")
    public Result del(@PathVariable("id") Integer id){
        int result = userService.del(id);
        return result > 0 ? Result.success("删除成功") : Result.success("删除失败");
    }
    @DeleteMapping("del/{id}")
    public Result delete(@PathVariable("id") Integer id){
        int result = userService.delete(id);
        return result > 0 ? Result.success("删除成功") : Result.success("删除失败");
    }

    @GetMapping("{id}")
    public Result one(@PathVariable("id") Integer id){
        UserBean user = userService.get(id);
        return user != null ? Result.success(user) : Result.success("用户不存在");
    }

    @GetMapping("list")
    public Result list(UserBean user){
        List<UserBean> list = userService.list(user);
        return Result.success(list);
    }

    @GetMapping("page")
    public Result page(Page page, UserBean user){
        userService.page(page, user);
        return Result.success(page);
    }
    // 在 UserController 类中添加以下方法
    @PostMapping("validatePassword/{id}/{password}")
    public Result validatePassword(@PathVariable("id")Integer id,@PathVariable("password")String password) {
        if (id == null || password == null || password.isEmpty()) {
            return Result.fail(400, "参数不能为空");
        }
        boolean isValid = userService.validatePassword(id, password);
        return isValid ? Result.success("密码正确") : Result.fail(200, "密码错误");
    }

    // 新增：根据账号获取用户信息（用于注册时检查账号是否已存在）
    @GetMapping("byNumber/{userNumber}")
    public Result getByNumber(@PathVariable("userNumber") String userNumber) {
        UserBean user = userService.getByNumber(userNumber);
        if (user != null) {
            return Result.success("账号已存在", user);
        } else {
            return Result.fail(200, "账号不存在");
        }
    }
    // 发送邮箱验证码
    @PostMapping("sendEmailCode")
    public Result sendEmailCode(@RequestBody Map<String, String> params) {
        String userNumber = params.get("userNumber");
        String email = params.get("email");

        if (userNumber == null || userNumber.isEmpty()) {
            return Result.fail(400, "账号不能为空");
        }
        if (email == null || email.isEmpty()) {
            return Result.fail(400, "邮箱不能为空");
        }

        // 验证账号是否存在
        UserBean user = userService.getByNumber(userNumber);
        if (user == null) {
            return Result.fail(200, "账号不存在");
        }

        // 验证邮箱是否匹配
        if (!email.equals(user.getUserEmail())) {
            return Result.fail(200, "邮箱与账号不匹配");
        }

        try {
            // 生成验证码
            String code = verificationCodeService.generateCode();
            // 发送邮件
            String result = EmailUtil.sendVerificationCode(email, code);
            if (result.equals("发送成功")) {
                // 存储验证码，key为账号+邮箱的组合
                String key = userNumber + "_" + email;
                verificationCodeService.storeCode(key, code);
                return Result.success("验证码发送成功");
            } else {
                return Result.fail(500, result);
            }
        } catch (Exception e) {
            return Result.fail(500, "发送验证码失败: " + e.getMessage());
        }
    }

    // 通过邮箱验证码修改密码
    @PostMapping("resetPasswordByEmail")
    public Result resetPasswordByEmail(@RequestBody Map<String, Object> params) {
        String userNumber = (String) params.get("userNumber");
        String email = (String) params.get("email");
        String code = (String) params.get("code");
        String newPassword = (String) params.get("newPassword");
        String confirmPassword = (String) params.get("confirmPassword");

        // 参数验证
        if (userNumber == null || userNumber.isEmpty()) {
            return Result.fail(400, "账号不能为空");
        }
        if (email == null || email.isEmpty()) {
            return Result.fail(400, "邮箱不能为空");
        }
        if (code == null || code.isEmpty()) {
            return Result.fail(400, "验证码不能为空");
        }
        if (newPassword == null || newPassword.isEmpty()) {
            return Result.fail(400, "新密码不能为空");
        }
        if (confirmPassword == null || confirmPassword.isEmpty()) {
            return Result.fail(400, "确认密码不能为空");
        }
        if (!newPassword.equals(confirmPassword)) {
            return Result.fail(400, "两次输入的密码不一致");
        }
        if (newPassword.length() < 6 || newPassword.length() > 16) {
            return Result.fail(400, "密码长度应在6-16位之间");
        }

        // 验证账号是否存在
        UserBean user = userService.getByNumber(userNumber);
        if (user == null) {
            return Result.fail(200, "账号不存在");
        }

        // 验证邮箱是否匹配
        if (!email.equals(user.getUserEmail())) {
            return Result.fail(200, "邮箱与账号不匹配");
        }

        // 验证验证码
        String key = userNumber + "_" + email;
        if (!verificationCodeService.verifyCode(key, code)) {
            return Result.fail(200, "验证码错误或已过期");
        }

        try {
            // 更新密码
            user.setUserPassword(newPassword);
            UserBean updatedUser = userService.edit(user);

            // 移除已使用的验证码
            verificationCodeService.removeCode(key);

            return Result.success("密码重置成功");
        } catch (Exception e) {
            return Result.fail(500, "密码重置失败: " + e.getMessage());
        }
    }

}
